package com.guit.hrms.controller;

import com.guit.hrms.dto.recuitmentDTO.AddPositions;
import com.guit.hrms.dto.recuitmentDTO.DeletePositions;
import com.guit.hrms.dto.recuitmentDTO.RecruitmentDTO;
import com.guit.hrms.po.recruitmentPO.FileEntity;
import com.guit.hrms.po.recruitmentPO.PlanDeptJob;
import com.guit.hrms.po.utilsPO.Result;
import com.guit.hrms.service.RecruitmentService;
import com.guit.hrms.vo.recruitmentVO.RecruitmentVO;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/api/recruit/announcements")
public class RecruitmentController {

    @Autowired
    RecruitmentService recruitmentService;

    // 允许的文件类型
    private static final List<String> ALLOWED_CONTENT_TYPES = Arrays.asList(
        "application/pdf",                     // PDF文件
        "application/msword",                  // doc
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // docx
        "application/vnd.ms-excel",            // xls
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",      // xlsx
        "image/jpeg",                          // jpg/jpeg
        "image/png"                            // png
    );
    
    // 最大文件大小 (10MB)
//    @Value("${spring.servlet.multipart.max-file-size")
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024;

    /**
     * 新增招聘公告
     * @param recruitmentDTO 招聘公告信息
     * @return Result
     */
    @PostMapping
    @Validated
    public Result newRecruitment(@Valid @RequestBody RecruitmentDTO recruitmentDTO) {

        if (recruitmentDTO.getPlanType() != 3) {
            //校验岗位和部门是否存在
            //1：没问题  2：部门不存在  3：岗位不存在
            Integer flag = recruitmentService.verifyAddCondition(recruitmentDTO);
            if (flag == 2) {
                return Result.error("该部门/学院编号不存在");
            }else if (flag == 3){
                return Result.error("该岗位编号不存在");
            }
        }
        //添加招聘公告
        recruitmentService.newRecruitment(recruitmentDTO);


        return Result.success();
    }

    /**
     * 上传附件
     */
    @PatchMapping("/attachments")
    public Result uploadAttachment(@RequestParam Integer planId, 
                                 @RequestParam MultipartFile attachments) {
        try {
            // 1. 验证文件是否为空
            if (attachments.isEmpty()) {
                return Result.error("请选择要上传的文件");
            }

            // 2. 验证文件大小
            if (attachments.getSize() > MAX_FILE_SIZE) {
                return Result.error("文件大小不能超过10MB");
            }

            // 3. 验证文件类型
            String contentType = attachments.getContentType();
            if (!ALLOWED_CONTENT_TYPES.contains(contentType)) {
                return Result.error("不支持的文件类型，仅支持PDF、Word、Excel和图片格式");
            }

            // 4. 获取并处理原始文件名
            String originalFilename = attachments.getOriginalFilename();
            if (originalFilename == null || originalFilename.trim().isEmpty()) {
                return Result.error("文件名不能为空");
            }
            
            // 5. 清理文件名(移除路径信息，只保留文件名)
            String fileName = new File(originalFilename).getName();
            
            // 6. 上传文件
            Integer result = recruitmentService.addFileToRecruitmentPlan(planId, attachments, fileName);
            return result > 0 ? Result.success() : Result.error("上传失败");
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return Result.error(e.getMessage());
        }
    }

//    /**
//     * 获取文件扩展名
//     */
//    private String getFileExtension(String filename) {
//        if (filename == null) return "";
//        int lastDotIndex = filename.lastIndexOf(".");
//        return lastDotIndex == -1 ? "" : filename.substring(lastDotIndex);
//    }
//
//    /**
//     * 生成规范的文件名
//     */
//    private String generateFileName(Integer planId, String extension) {
//        LocalDateTime now = LocalDateTime.now();
//        return String.format("recruitment_plan_%d_%s%s",
//            planId,
//            now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),
//            extension);
//    }

    /**
     * 获取招聘公告
     * @return Result
     */
    @GetMapping("/get")
    public Result getRecruitment() {

        List<RecruitmentVO> recruitmentVOList = recruitmentService.queryRecruitment();
        return Result.success(recruitmentVOList);
    }

    /**
     * 修改招聘公告
     * @param planDeptJob 招聘公告信息
     * @return Result
     */
    @PatchMapping
    @Validated
    public Result updateRecruitment(@Valid @RequestBody PlanDeptJob planDeptJob) {
        log.info("收到更新请求，参数：{}", planDeptJob);
        
        String numbering = planDeptJob.getNumbering();
        String positionName = planDeptJob.getPositionName();
        String jobDescription = planDeptJob.getJobDescription();
        String jobRequired = planDeptJob.getJobRequired();
        Integer person = planDeptJob.getPerson();
        String content = planDeptJob.getContent();
        Integer professionalSkillsRight = planDeptJob.getProfessionalSkillsRight();
        Integer communicationSkillsRight = planDeptJob.getCommunicationSkillsRight();
        Integer teamworkAbilityRight = planDeptJob.getTeamworkAbilityRight();

        if (((numbering == null || positionName == null)
                || (jobDescription == null && jobRequired == null && person == null
                && professionalSkillsRight == null && communicationSkillsRight == null 
                && teamworkAbilityRight == null))) {
            if (content == null){
                log.warn("无字段更新");
                return Result.error("无字段更新！");
            } else {
                log.info("更新其他计划内容");
                recruitmentService.updateOtherPlan(planDeptJob);
            }
        } else {
            log.info("更新招聘计划岗位信息");
            recruitmentService.updatePlanDeptJob(planDeptJob);
        }
        return Result.success();
    }

    /**
     * 删除招聘公告
     * @param planId 招聘计划id
     * @return Result
     */
    @DeleteMapping
    public Result deleteRecruitment(@RequestParam @NotNull(message = "planId不能为空") Integer planId) {

        recruitmentService.deletePlanDeptJob(planId);
        return Result.success();
    }

    /**
     * 下载附件
     */
    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadFile(@RequestParam Integer planId) {
        try {
            FileEntity fileEntity = recruitmentService.getFile(Long.valueOf(planId));
            if (fileEntity == null || fileEntity.getAttachments() == null) {
                return ResponseEntity.notFound().build();
            }

            // 获取文件名并处理中文编码
            String fileName = fileEntity.getFileName();
            log.info("原始文件名: {}", fileName);  // 打印原始文件名
            
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8)
                    .replaceAll("\\+", "%20");  // 处理空格
            log.info("编码后的文件名: {}", encodedFileName);  // 打印编码后的文件名
            
            String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s", 
                    encodedFileName, encodedFileName);
            log.info("Content-Disposition: {}", contentDisposition);  // 打印完整的 header 值

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(fileEntity.getContentType()))
                    .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
                    .body(fileEntity.getAttachments());
        } catch (Exception e) {
            log.error("文件下载失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 新增用人部门
     * @param newPostDTO 用人部门信息
     * @return Result
     */
    /*@PostMapping("/positions")
    @Validated
    public Result newPlanDeptJob(@Valid @RequestBody NewPostDTO newPostDTO){

        String[] verifyRS =  recruitmentService.verify(newPostDTO);
        if (verifyRS[0].equals(VerifyRS.NotPassed)){
            return Result.error(verifyRS[1]);
        }

        recruitmentService.newPlanDeptJob(newPostDTO);

        return Result.success();
    }*/

    /**
     * 删除用人部门
     * @param delPositons 用人部门信息
     * @return Result
     */
    /*@DeleteMapping("/positions")
    @Validated
    public Result deletePlanDeptJob(@Valid @RequestBody DeletePositionsRequest delPositons ){

        String[] verifyRS =  recruitmentService.verifyPlanDeptJobPrimaryKey(delPositons);

        if (verifyRS[0].equals(VerifyRS.NotPassed)){
            return Result.error(verifyRS[1]);
        }

        recruitmentService.deletePlanDeptJobByAllPrimaryKey(delPositons);

        return Result.success();
    }*/

    /**
     * 新增用人部门岗位
     * @param addPositions
     * @return
     */
    @PostMapping("/positions")
    @Validated
    public Result addPost(@Valid @RequestBody AddPositions addPositions) {
        if (addPositions.getPlanType() != 1 && addPositions.getPlanType() != 2) {
            return Result.error("请选择部门或二级学院");
        }
        try {
            recruitmentService.addPost(addPositions.getPlanType(), addPositions.getPlanId(), addPositions.getDepts());
            return Result.success();
        } catch (RuntimeException e) {
            // 将详细错误信息放入 msg 字段返回给前端
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除用人部门岗位
     * @param delPositions 用人部门信息
     * @return Result
     */
    @DeleteMapping("/positions")
    @Validated
    public Result delPost(@Valid @RequestBody DeletePositions delPositions ){
        recruitmentService.deletePost(delPositions);
        return Result.success();
    }

    /**
     * 获取附件信息
     */
    @GetMapping("/attachments/{planId}")
    public Result getAttachmentInfo(@PathVariable Integer planId) {
        try {
            FileEntity fileEntity = recruitmentService.getFile(Long.valueOf(planId));
            if (fileEntity == null || fileEntity.getAttachments() == null) {
                return Result.error("未找到附件");
            }
            
            Map<String, Object> fileInfo = new HashMap<>();
            fileInfo.put("fileName", fileEntity.getFileName());
            fileInfo.put("contentType", fileEntity.getContentType());
            fileInfo.put("fileSize", fileEntity.getAttachments().length);
            
            return Result.success(fileInfo);
        } catch (Exception e) {
            log.error("获取文件信息失败", e);
            return Result.error(e.getMessage());
        }
    }

}
